package com.id.coinscleaner.utils

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.core.os.bundleOf
import androidx.viewbinding.BuildConfig

import com.google.firebase.analytics.FirebaseAnalytics


data class EventObject(val key: String, val params: Any?)

class FirebaseEventsService(context: Context) : EventsService() {

    private val firebaseAnalytics by lazy { FirebaseAnalytics.getInstance(context) }

    override fun sendEvent(name: String) {
        sendEvent(name, mapOf())
    }

    override fun sendEvent(name: String, params: Map<String, Any?>) {
        if (BuildConfig.DEBUG) {
            Log.d("EventService", "name: $name, params: $params")
        } else {
            firebaseAnalytics.logEvent(name, params.asBundle())
        }
    }

    private fun <V> Map<String, V>.asBundle() = bundleOf(*map { it.key to it.value }.toTypedArray())
}

abstract class EventsService {
    abstract fun sendEvent(name: String)

    abstract fun sendEvent(name: String, params: Map<String, Any?>)
}


object Events {

    private lateinit var service: Array<out EventsService>

    fun initialize(vararg service: EventsService) {
        Events.service = service
    }

    @JvmStatic
    fun sendEvent(name: String) {
        service.forEach { it.sendEvent(name) }
    }

    @JvmStatic
    fun sendEvent(name: String, params: Map<String, Any?>) {
        service.forEach { it.sendEvent(name, params) }
    }

    @JvmStatic
    fun sendEvent(name: String, params: Pair<String, *>) {
        sendEvent(name, mapOf(params))
    }

    @JvmStatic
    fun sendEvent(name: String, bundle: Bundle) {
        val params = bundle.keySet().associateWith {
            bundle.get(it)
        }
        sendEvent(name, params)
    }

}
